package com.rpc.demo.consumer.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * @Author: ZhaoJie
 * @Date: 2022/4/8
 * @Description:
 * @Modify: ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */

public class ConsumerNettyServer {

    public ConsumerNettyServer(String hostName, int port, ChannelInboundHandlerAdapter handler) {
        initClient(hostName, port, handler);
    }

    //初始化客户端
    private static void initClient(String hostName, int port, ChannelInboundHandlerAdapter handler) {
        //创建EventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(
                        new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                                pipeline.addLast(new ObjectEncoder());
                                pipeline.addLast(handler);
                            }
                        }
                );

        try {
            bootstrap.connect(hostName, port).sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
